#include "fat32.h"
#include "ourhdr.h"

int init_struct_fat32(const char* device, struct filsys_fat32* fs){
	int fd;
	if( (fd = open(device, O_RDONLY)) < 0){
		fprintf(stderr, "fail to open %s\n", device);
		return -1;
	}
	fs->device = device;
	fs->tot_sz = lseek(fd, 0, SEEK_END);
	fs->tot_secs = fs->tot_sz / SEC_SZ;
	fs->clus_sz = CLUS_SZ;
	fs->fat_start = FAT_START;
	fs->fat_secs = FAT_ENT_SZ * (fs->tot_secs - RSVD_SECS) / (FAT_ENT_SZ * FAT_NUM + CLUS_SZ);
	fs->data_start = FAT_START + fs->fat_secs * FAT_NUM;
	fs->data_secs = fs->tot_secs - fs->data_start - 1;
	fs->clus_num = fs->data_secs / SECS_PER_CLUS;

	fs->dir_clus = (2 + INDEXS_PER_PACK + VIDEOS_PER_PACK + CLUS_SZ/(sizeof(SHORT_FDT)) - 1) / (CLUS_SZ/sizeof(SHORT_FDT));
	uint32_t appendix_clus =	(fs->dir_clus + INDEXS_PER_PACK * INDEX_CLUS);
	uint32_t full_folder_clus = (VIDEOS_PER_PACK * VIDEO_CLUS + appendix_clus);
	fs->folder_cnt = (fs->clus_num - ROOT_CLUSTERS - ALLOC_CLUS + full_folder_clus - appendix_clus) / full_folder_clus;
	fs->last_folder_file_cnt = (fs->clus_num - (fs->folder_cnt - 1) * full_folder_clus - appendix_clus) / VIDEO_CLUS;
	disp(fs->dir_clus);
	disp(fs->folder_cnt);
	disp(fs->last_folder_file_cnt);
	close(fd);
}
